// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.asm;

import java.io.IOException;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

public final class RepeatableClassLoader extends ClassLoader {
  
  public RepeatableClassLoader() {
    super();
  }

  public RepeatableClassLoader(ClassLoader base) {
    super(base);
  }

  @Override 
  protected Class findClass(String name) throws ClassNotFoundException { 
    if (name.endsWith("_Repeatable")) {
      String orgName = name.substring(0, name.length() - "_Repeatable".length());
      ClassReader classReader;
      try {
        classReader = new ClassReader(orgName);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
      ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
      ClassVisitor out = new RepeatableClassVisitor(classWriter, name.replace('.', '/'));
      classReader.accept(out, 0);
      byte[] b = classWriter.toByteArray(); 
      return defineClass(name, b, 0, b.length); 
    } 
    return super.findClass(name); 
  }
}